package ddhost.cbs;

import java.util.Set;
import android.app.Activity;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;


public class Main extends Activity {
	//サーチ周期の初期値
	private int defCycleMin = 5,defCycleHour=0;
	
	private  class btTimerReceiver extends BroadcastReceiver {
		public Main main;
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// 周期的にここの処理が実行される
			
			
			//Bluetoothあるか
			BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			if (mBluetoothAdapter == null) {
				Toast toast = Toast.makeText(getApplicationContext(), "ERROR:NO BD FOUND!", Toast.LENGTH_LONG);
				toast.show();
			    return;
			}
			
			//BluetoothをONに
			if (!mBluetoothAdapter.isEnabled()) {
				Toast toast = Toast.makeText(getApplicationContext(), "ERROR:ENABLE BD AT FIRST!", Toast.LENGTH_LONG);
				toast.show();
			    mBluetoothAdapter.enable();
			    return;
			}
			
			//もしサーチ中ならサーチ止める
			if(mBluetoothAdapter.isDiscovering()){
				mBluetoothAdapter.cancelDiscovery();
			}
			
			//サーチ中止中にやりたい処理はこの部分に
			//たとえばログのアップロードとか
			
			
			// すでにペアリングされたデバイスを取得
			Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
			// If there are paired devices
			if (pairedDevices.size() > 0) {
			    // Loop through paired devices
			    //for (BluetoothDevice device : pairedDevices) {
			        // Add the name and address to an array adapter to show in a ListView
			        //mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
			    //}
				Toast toast = Toast.makeText(getApplicationContext(), "DISCONNECT PAREINGs AT FIRST!", Toast.LENGTH_LONG);
				toast.show();
				return;
			}
			
			//BDを見つけた時の処理
			final BroadcastReceiver mReceiver = new BroadcastReceiver() {
			    public void onReceive(Context context, Intent intent) {
			        String action = intent.getAction();
			        // When discovery finds a device
			        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
			            // Get the BluetoothDevice object from the Intent
			            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			            // Add the name and address to an array adapter to show in a ListView
			            //mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
			            
			            //ログファイルに書き込む
			            fileWriteThread fwt = new fileWriteThread(device.getAddress()+" "+device.getName());
			            fwt.start();
			            
			            //Toastに表示
						Toast toast = Toast.makeText(getApplicationContext(), "FOUND:"+device.getName(), Toast.LENGTH_LONG);
						toast.show();
			        }
			    }
			};
			// BDを見つけた時の処理を登録
			IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
			registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
			
			// BDサーチ開始
			Toast toast = Toast.makeText(getApplicationContext(), "Discoverying...", Toast.LENGTH_LONG);
			toast.show();
			mBluetoothAdapter.startDiscovery();
			
			
			////////// もう一回サービスをスタート
			TimePicker timePicker = (TimePicker)findViewById(R.id.TimePicker01);
			timePicker.setIs24HourView(true);
			timePicker.setCurrentHour(defCycleHour);
			timePicker.setCurrentMinute(defCycleMin);
			long hour = timePicker.getCurrentHour();
			long min = timePicker.getCurrentMinute();			
			btTimerService.schedule((hour * 60 + min) * 60 * 1000);
			moveTaskToBack(true);
			
		}
		
	}
	
	private TimerService btTimerService;
	private final btTimerReceiver receiver = new btTimerReceiver();
	
	private ServiceConnection serviceConnection = new ServiceConnection() {
		
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			btTimerService = ((TimerService.btTimerBinder)service).getService();
		}
		
		@Override
		public void onServiceDisconnected(ComponentName className) {
			btTimerService = null;
		}
		
	};
	
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

		final TimePicker timePicker = (TimePicker)findViewById(R.id.TimePicker01);
		timePicker.setIs24HourView(true);
		timePicker.setCurrentHour(0);
		timePicker.setCurrentMinute(defCycleMin);
		
		Button button = (Button)findViewById(R.id.Button01);
		button.setOnClickListener(new View.OnClickListener() {
		
			public void onClick(View view) {
				//サービススタート
				long hour = timePicker.getCurrentHour();
				long min = timePicker.getCurrentMinute();
				defCycleHour = (int)hour;
				defCycleMin = (int)min;
				
				
				btTimerService.schedule((hour * 60 + min) * 60 * 1000);
				
				//この画面をhideする
				moveTaskToBack(true);
			}
			
		});
		
		receiver.main = this;
		
		// サービスを開始
		Intent intent = new Intent(this, TimerService.class);
		startService(intent);
		IntentFilter filter = new IntentFilter(TimerService.ACTION);
		registerReceiver(receiver, filter);
		
		// サービスにバインド
		bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

		// いったんアンバインドしてから再度バインド
		unbindService(serviceConnection);
		bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
		
		errorLogWriter logw = new errorLogWriter("STARTED");
		logw.start();
		
		
		// HIDEボタンのハンドラを追加
		Button btnHide = (Button)findViewById(R.id.btnHide);
		btnHide.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {				
				//この画面をhideする
				moveTaskToBack(true);
			}
		});
		
		// QUITボタンのハンドラを追加
		Button btnQuit = (Button)findViewById(R.id.btnQuit);
		btnQuit.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				//この画面を終了する
				finish();
			}
		});
	}
	
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unbindService(serviceConnection); // バインド解除
		unregisterReceiver(receiver); // 登録解除
		btTimerService.stopSelf(); // サービスは必要ないので終了させる。
	}
	
	
	// Backキーが押されたとき，アプリを終了せずに画面を隠す．
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(keyCode != KeyEvent.KEYCODE_BACK){
    		return super.onKeyDown(keyCode, event);
    	}else{
    		//return false;
    		
    		//この画面をhideする
			moveTaskToBack(true);
			return true;
    	}
    }
	
}